package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.constant.MessageConstant;
import com.chen.exception.BaseException;
import com.chen.mapper.NodeMapper;
import com.chen.mapper.RegionMapper;
import com.chen.mapper.VendingMachineMapper;
import com.chen.mapper.VmTypeMapper;
import com.chen.pojo.common.PageResult;
import com.chen.pojo.dto.NodeDto;
import com.chen.pojo.entry.Node;
import com.chen.pojo.entry.Region;
import com.chen.pojo.entry.VendingMachine;
import com.chen.pojo.entry.VmType;
import com.chen.pojo.vo.*;
import com.chen.service.NodeService;
import com.chen.utils.PageUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chen
 * @version 1.0
 * @create_date 2025/8/17
 * 点位管理业务实现类
 */
@Service
@Transactional
public class NodeServiceImpl implements NodeService {
    @Autowired
    private NodeMapper nodeMapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private VendingMachineMapper vendingMachineMapper;
    @Autowired
    private VmTypeMapper vmTypeMapper;

    /**
     * 分页查询
     *
     * @param pageIndex 起始页
     * @param pageSize  页大小
     * @param name      点位名称
     * @param regionId  区域id
     * @return 查询结果
     */
    @Override
    public PageResult<NodeVo> searchList(Integer pageIndex, Integer pageSize, String name, String regionId) {
        Page<NodeVo> page = new Page<>(pageIndex, pageSize);
        nodeMapper.selectPageNode(page, name, regionId);
        List<NodeVo> records = page.getRecords();

        // 获取region对象
        if (!CollectionUtils.isEmpty(records)) {
            List<String> ids = records.stream().map(NodeVo::getRegionId).toList();
            Map<String, RegionVo> regionMap = regionMapper.selectRegionByIds(ids).stream().collect(Collectors.toMap(Region::getId, s -> s));
            records.forEach(s -> s.setRegion(regionMap.get(s.getRegionId())));
        }
        page.setRecords(records);
        return PageUtils.mapperResult(page);
    }

    /**
     * 新增点位
     *
     * @param nodeDto 点位信息
     * @return 结果
     */
    @Override
    public Boolean addNode(NodeDto nodeDto) {
        Node node = new Node();
        BeanUtils.copyProperties(nodeDto, node);
        node.setCreateTime(LocalDateTime.now());
        node.setUpdateTime(LocalDateTime.now());
        nodeMapper.insert(node);
        return true;
    }

    /**
     * 获取点位详情
     *
     * @param nodeId 点位id
     * @return
     */
    @Override
    public List<DetailVo> getNodeDetail(String nodeId) {
        List<DetailVo> resultList = new ArrayList<>();
        // 查询tb_vending_machine表信息
        LambdaQueryWrapper<VendingMachine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VendingMachine::getNodeId, nodeId);
        List<VendingMachine> result = vendingMachineMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(result)) {
            throw new BaseException(MessageConstant.DATE_NOT_FOUND);
        }

        // 查询区域表信息
        List<String> regionIds = result.stream().map(VendingMachine::getRegionId).toList();
        Map<String, RegionVo> regionMap = regionMapper.selectRegionByIds(regionIds).stream()
                .collect(Collectors.toMap(Region::getId, s -> s));

        // 查询机械类型信息
        List<Integer> typeIds = result.stream().map(VendingMachine::getVmType).distinct().toList();
        Map<Integer, VmType> vmTypeMap = vmTypeMapper.selectBatchIds(typeIds).stream()
                .collect(Collectors.toMap(VmType::getTypeId, s -> s));

        // 查询点位信息
        List<NodeVo> nodes = nodeMapper.selectNodeByIds(List.of(nodeId));
        NodeVo nodeVo = null;
        if (!CollectionUtils.isEmpty(nodes)) {
            nodeVo = nodes.get(0);
            Map<String, RegionVo> nodeRegionMap = regionMapper.selectRegionByIds(List.of(nodeVo.getRegionId()))
                    .stream().collect(Collectors.toMap(Region::getId, s -> s));
            nodeVo.setRegion(nodeRegionMap.get(nodeVo.getRegionId()));
        }

        for (VendingMachine s : result) {
            DetailVo detailVo = new DetailVo();
            VmTypeVo vmTypeVo = new VmTypeVo();
            BeanUtils.copyProperties(vmTypeMap.get(s.getVmType()), vmTypeVo);
            BeanUtils.copyProperties(s, detailVo);
            detailVo.setType(vmTypeVo);
            detailVo.setRegion(regionMap.get(s.getRegionId()));
            detailVo.setNode(nodeVo);
            resultList.add(detailVo);
        }
        return resultList;
    }

    @Override
    public Boolean updateNode(String nodeId, NodeDto nodeDto) {
        Node node = new Node();
        BeanUtils.copyProperties(nodeDto, node);
        node.setUpdateTime(LocalDateTime.now());
        node.setId(nodeId);
        nodeMapper.updateById(node);
        return true;
    }

    /**
     * 删除点位信息
     *
     * @param nodeId 点位id
     * @return 结果
     */
    @Override
    public Boolean deleteNode(String nodeId) {
        nodeMapper.deleteById(nodeId);
        return true;
    }

    /**
     * 统计点位数量
     *
     * @return 点位数量
     */
    @Override
    public Long getNodeCount() {
        return nodeMapper.selectCount(null);
    }

    /**
     * 合作商点位汇总统计
     *
     * @return 结果
     */
    @Override
    public List<ReportVo> getNodeCountByPartner() {
        return nodeMapper.selectNodeCountByPartner();
    }
}
